<!DOCTYPE html>
<html>

<head>
    <title> How to bind function in React? </title>
    <script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin></script>
</head>

<body>
    <div id="root"></div>
</body>

</html>
<script type="text/babel">
    class Toggle extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                isToogle: true,
            }
            // Way 1 : Call  bind
            // If callback函数很少，推荐使用.
            // If callback函数很多，不推荐使用。因为要写很多类似 this._handClick 的变量。
            // 只绑定_handClick1次。
            // This binding is necessary to make 'this' work in the onClick callback.
            this._handClick = this.handClick.bind(this);
        }

        handClick() {
            this.setState(function (prevState) {
                return {
                    isToogle: !prevState.isToogle,
                }
            });
        }
        render() {
            // 读取变量 this._handClick
            // button 里面的this 本来指向button这个上下文。上面使用bind，把this强制指向了Toggle。
            return (<button onClick={this._handClick}>
                {this.state.isToogle ? "ON" : "OFF"}
            </button>);
        }
    }

    ReactDOM.render(<Toggle />, document.getElementById('root'));
</script>